package org.alexl.webhook.service.impl;

import org.alexl.webhook.domain.PushObject;
import org.alexl.webhook.exception.BadPasswordException;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.alexl.webhook.service.IWebHookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

/**
 *
 * @author Alexander
 */
@Service
@Slf4j
public class WebHookService implements IWebHookService {
    @Autowired
    private Environment env;

    @Override
    public boolean execute(PushObject obj) throws BadPasswordException, IOException, InterruptedException {
        log.info("processing {}", obj);
        // 验证密码
        validatePassword(obj);
        
        String dir = env.getProperty(String.format("%s.dir", obj.getProject()));
        String command = env.getProperty(String.format("%s.command", obj.getProject()));
        // 获取命令完整路径
        command = new File(dir, command) + String.format(
                " &> ./log/%s_%s.log", 
                obj.getProject(),
                new SimpleDateFormat("yyyyMMddhhmmssS", Locale.CHINA).format(new Date()));
        log.debug("execute command: {}", command);
        Process process = Runtime.getRuntime().exec(
                new String[] {"bash", "-c", command}, 
                new String[] {"JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.144-0.b01.el7_4.x86_64/"}, new File(dir));
        boolean result = process.waitFor(60, TimeUnit.SECONDS);
        log.info("finish to deploy {}", obj.getProject());
        return result;
    }
    
    private void validatePassword(PushObject obj) throws BadPasswordException {
        if (!obj.getPassword().equals(env.getProperty(String.format("%s.password", obj.getProject())))) {
            log.error("validate password: FAIL");
            throw new BadPasswordException(obj.getPassword());
        }
        log.debug("validate password: PASS");
    }
    
}
